﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using SYSoft.Comm;
using SYSoft.Model;
using SYSoft.Model.Models.DeviceManage.StockCheck;
using SYSoft.Models;
using SYSoft.Services.StockCheckManage;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace SYSoft.Controllers.StockCheckManage
{
    public class CheckManageController : BaseController
    {
        private readonly IHostingEnvironment _hostingEnvironment;

        ICheckManageService checkManage;
        ICheckDataService checkData;
        public CheckManageController(IHostingEnvironment hostingEnvironment,ICheckManageService checkManage, ICheckDataService checkData)
        {
            this.checkManage = checkManage;
            this.checkData = checkData;
            _hostingEnvironment = hostingEnvironment;
        }


        /// <summary>
        /// 获取基础库该设备名称
        /// </summary>
        /// <param name="devicename">2012-09-21</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<List<string>>> GetAllDeviceName()
        {
            
            var model = await checkManage.Query(x=>x.CreatTime< Convert.ToDateTime("1999-11-11 23:00:00"));
            if (model != null && model.Count > 0)
            {
                List<string> str = new List<string>();
                for (int i = 0; i < model.Count; i++)
                {
                    if (!str.Contains(model[i].DeviceFlag))
                        str.Add(model[i].DeviceFlag);
                }
                return MessageModel.CreateSuccessResult(str);
            }
            return MessageModel.CreateFailedResult<List<string>>("");
        }


        /// <summary>
        /// 添加设备
        /// </summary>
        /// <param name="devicename">2012-09-21</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel> PostDeviceName(string devicename)
        {
            CheckTask_Baselib model = new CheckTask_Baselib
            {
                CreatTime = Convert.ToDateTime("1998-11-11 00:00:00"),
                DeviceFlag = devicename,
            };
            var res = await checkManage.Add(model);
            if (res > 0)
            {
                return MessageModel.CreateSuccessResult();
            }
            return new  MessageModel("添加设备失败！！");
        }





        /// <summary>
        /// 获取基础库该设备所有任务
        /// </summary>
        /// <param name="devicename">2012-09-21</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<PageModel<CheckTask_Baselib>>> GetTasksByDeviceName(string devicename, int page=1, int size=10)
        {

            var model = await checkManage.QueryPage((item => item.DeviceName == devicename), page, size);
            if (model.data != null && model.data.Count > 0)
            {
                return MessageModel.CreateSuccessResult(model);
            }
            return MessageModel.CreateFailedResult<PageModel<CheckTask_Baselib>>("");
        }


        ///// <summary>
        ///// 新增点检任务计划
        ///// </summary>
        ///// <returns></returns>
        //[HttpPost]
        //public async Task<MessageModel<int>> PostTask([FromBody] CheckTask_Baselib model)
        //{
        //   var res = await checkManage.Add(model);
        //    if (res > 0)
        //        return MessageModel.CreateSuccessResult(res);
        //    else
        //        return MessageModel.CreateFailedResult<int>("Id必须大于0");
        //}


        [HttpPost]
        public async Task<MessageModel> UpLoadImg([FromForm] UploadDjModel model)
        {
            try
            {                               
                CheckTask_Baselib db = new CheckTask_Baselib
                {
                    DeviceId = model.DeviceId,
                    DeviceName = model.DeviceName,
                    DevicePosition = model.DevicePosition,
                    TaskName = model.TaskName,
                    TaskContent = model.TaskContent,    
                    TaskImage =model.TaskImage,
                };

                if (model.TaskImgfile != null)
                {
                    string uploadsFolder = Path.Combine(_hostingEnvironment.WebRootPath, "standimage");
                    string uniqueFileName = Guid.NewGuid().ToString() + "_" + model.TaskImgfile.FileName;
                    string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                    model.TaskImgfile.CopyTo(new FileStream(filePath, FileMode.Create));

                    db.TaskImage = "http://localhost:8081/standimage/" + uniqueFileName;
                }

                if (model.UpModelType == 0)
                {
                    
                    var  res = await checkManage.Add(db);
                    if (res > 0)
                    {
                        Check_Task task = new Check_Task
                        {
                            DeviceId = db.DeviceId,
                            DeviceName = db.DeviceName,
                            DevicePosition = db.DevicePosition,
                            TaskContent = db.TaskContent,
                            TaskImage = db.TaskImage,
                            TaskName = db.TaskName,
                            StartCheckTime = DateTime.Now,
                            CreatTime = DateTime.Now,
                        };
                        await checkData.Add(task);
                        return MessageModel.CreateSuccessResult(res);
                    }
                       
                    else
                        return MessageModel.CreateFailedResult<int>("Id必须大于0");
                }
                    
                else
                {
                    db.Id = model.Id;
                    var res = await checkManage.Update(db);
                    if (res)
                        return MessageModel.CreateSuccessResult(res);
                    else
                        return MessageModel.CreateFailedResult<int>("修改失败！！");
                }             
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.Message);
                return MessageModel.CreateFailedResult<int>(ex.Message);
            }
            

        }

        ///// <summary>
        ///// 修改用户信息
        ///// </summary>
        ///// <param name="user"></param>
        ///// <returns></returns>
        //[HttpPut]
        //public async Task<MessageModel<string>> Update([FromBody] CheckTask_Baselib model)
        //{
        //    model.UpdateTime = DateTime.Now;
        //    //sysUserInfo.UpdateBy = Operator.UserId; //操作者
        //    var res = await checkManage.Update(model);
        //    if (res)
        //        return MessageModel.CreateSuccessResult<string>("sucess");
        //    return MessageModel.CreateFailedResult<string>("修改任务信息失败！！");
        //}

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<MessageModel<string>> Delete(int id)
        {
            if (id > 0)
            {
                var userDetail = await checkManage.QueryById(id);
                bool res = await checkManage.Delete(userDetail);
                if (!res)
                    return MessageModel.CreateFailedResult<string>("删除任务失败！！");
                return MessageModel.CreateSuccessResult("删除任务成功");
            }
            return MessageModel.CreateFailedResult<string>("Id必须大于0");
        }



    }
}
